package leetcode.editor.cn;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author: yangwk
 * @date: 2023/6/16
 * @description:
 **/
public class P295 {
    public static void main(String[] args) {
        P295 p295 = new P295();
        int[] arr = new int[]{-1, -2, -3, -4, -5};
        for (int i : arr) {
            p295.offer(i);
            System.out.println(p295.getMid());
        }
    }

    //小顶堆，存较大的数
    PriorityQueue<Integer> minQueue = new PriorityQueue<>((Comparator.comparingInt(o -> o)));
    //大顶堆，存较小的数
    PriorityQueue<Integer> maxQueue = new PriorityQueue<>((o1, o2) -> o2 - o1);

    public void offer(Integer val) {
        if (minQueue.isEmpty()) {
            minQueue.offer(val);
        } else {
            if (minQueue.size() - maxQueue.size() == 1) {
                if (val >= minQueue.peek()) {
                    maxQueue.offer(minQueue.poll());
                    minQueue.offer(val);
                } else {
                    maxQueue.offer(val);
                }
            } else {
                if (val >= minQueue.peek() || val >= maxQueue.peek()) {
                    minQueue.offer(val);
                } else {
                    minQueue.offer(maxQueue.poll());
                    maxQueue.offer(val);
                }
            }
        }
    }

    public double getMid() {
        if (minQueue.size() == maxQueue.size()) {
            return (minQueue.peek() + maxQueue.peek()) / 2.0;
        }
        return minQueue.size() > maxQueue.size() ? minQueue.peek() : maxQueue.peek();
    }
}
